package com.work.chat.common.util;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class AESUtil {
    /**
     * AES解密
     *
     * @param key     密钥
     * @param message 待解密信息
     * @return 解密后得到的原文；{@code null}意味着解密失败
     */
    public static String decrypt(String key, String message) {
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(Base64.getDecoder().decode(key), "AES"));
            byte[] decryptBytes = cipher.doFinal(Base64.getDecoder().decode(message));
            return new String(decryptBytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 加密信息
     *
     * @param key     密钥
     * @param message 待加密信息
     * @return 加密后得到的密文; {@code null}意味着加密失败
     */
    public static String encrypt(String key, String message) {
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(Base64.getDecoder().decode(key), "AES"));
            byte[] resultBytes = cipher.doFinal(message.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(resultBytes);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        String message = "123456";
        String key = "dOByVNUpTAoXwqghrbTcB7IEkIyYssss";
        String strEncrypted = encrypt(key, message);
        System.out.println(strEncrypted);
        String strDecrypted = decrypt(key, strEncrypted);
        System.out.println(strDecrypted);
    }
}